/**
 * 实际上用不上dfs
 * @param {number[][]} grid
 * @return {number}
 */
var islandPerimeter = function (grid) {
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === 1) {
                return dfs(grid, i, j)
            }
        }
    }
};

function dfs(grid, i, j) {
    grid[i][j] = 2
    let nodeSum = 4,
        direction = [[1, 0], [-1, 0], [0, 1], [0, -1]];
    for (let [x, y] of direction) {
        let newI = i + x,
            newJ = j + y;
        if (newI < 0 || newI >= grid.length || newJ < 0 || newJ >= grid[0].length) continue
        if (grid[newI][newJ] >= 1) {
            nodeSum--
        }
        if (grid[newI][newJ] === 1) {
            nodeSum += dfs(grid, newI, newJ)
        }
    }
    return nodeSum
}




/**
 * 这就行了
 * @param {number[][]} grid
 * @return {number}
 */
var islandPerimeter = function (grid) {
    let res = 0;
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === 1) {
                let nodeSum = 4,
                    direction = [[1, 0], [-1, 0], [0, 1], [0, -1]];
                for (let [x, y] of direction) {
                    let newI = i + x,
                        newJ = j + y;
                    if (newI < 0 || newI >= grid.length || newJ < 0 || newJ >= grid[0].length) continue
                    if (grid[newI][newJ] === 1) {
                        nodeSum--
                    }
                }
                res += nodeSum
            }
        }
    }
    return res
};
